list與tuple相似,不同的是,list可以更改(插入、刪除、取代)
使用[]建立list並以逗號(,)間隔
也可以使用與str、tuple一樣切片、連接(+)、複製(*)等運算符
例如
#list.py
location=[101,"taipei",["信義區","大安區"],"ximen"]
print(location[2:])
print(location[2][1])
print(location[2][0]*5+str(location[0]))
list.append(x) :將資料x附加至list的結尾處
list.extend(L) :將L中所有資料,附加至list的結尾處
list.insert(i, x) :指定list的i位置,插入資料x
list.remove(x) :由左開始尋找,移除第一次出現的資料x,
list.pop() :移除list最右邊的資料
list.pop(i) :移除索引值i位置的資料
list.index(x) :由左開始尋找,傳回x第一次出現的索引位製
list.count(x) :傳回x在list中出現的次數
list.sort() :排序list
list.reverse() :反轉list
如果型態不同,進行排序會引發例外
例如
#list.py
location=[101,"taipei",["信義區","大安區"],"ximen"]
location.sort()
例如
#list.py
location=[101,"taipei",["信義區","大安區"],"ximen"]
print(location)
location.append("tianmu")
print(location)
x = ["a","b","c"]
location.extend(x)
print(location)
location.insert(3,"beitou")
print(location)
location.remove("ximen")
print(location)
location.pop()
print(location)
location.pop(3)
print(location)
print(location.index(101))
print(location.count(101))
location = [2,1,3,5,7,10,11]
location.sort()
print(location)
location.reverse()
print(location)